package org.myy.learn.hot.finish.栈_1;

import java.util.*;

public class 有效括号 {
    /**
     * 字典映射
     * @param s
     * @return
     */
    private static boolean isValib1(String s){
        if(s.length()%2 != 0){return false;}
        Map<Character, Character> map = Map.ofEntries(
                Map.entry(')', '('),
                Map.entry(']', '['),
                Map.entry('}', '{')
        );
        /**
         * Queue普通队列   先进先出[首出尾进]
         * Deque双端队列   入队addFirst/Last(?)  | 出队pollFirst/Last
         *                pop出栈顶，peak看栈顶，pusk如栈顶
         */
        Deque<Character> deque = new LinkedList<>();
        for (Character c : s.toCharArray()){
            if(map.containsKey(c)){
                //右半边，是否配对成功
                if(deque.isEmpty() || !deque.peek().equals(map.get(c))){
                    return false;
                }
                deque.pop();
            }else{
                //左半边，无脑如队
                deque.push(c);
            }
        }
        return deque.isEmpty();
    }

    /**
     * swtich循环
     * @param s
     * @return
     */
    private static boolean isValib2(String s){
        if(s.length()%2 != 0){return false;}
        Deque<Character> deque = new LinkedList<>();
        for(Character c : s.toCharArray()){
            /**
             * 符号"："和break必不可少
             */
            switch (c){
                case '(':
                case '{':
                case '[':
                    deque.push(c);
                    break;
                case ')':
                    if(deque.isEmpty() || !deque.peek().equals('(')){
                        return false;
                    }
                    deque.pop();
                    break;
                case '}':
                    if(deque.isEmpty() || !deque.peek().equals('{')){
                        return false;
                    }
                    deque.pop();
                    break;
                case ']':
                    if(deque.isEmpty() || !deque.peek().equals('[')){
                        return false;
                    }
                    deque.pop();
                    break;
                default:
                    return false;  //非法字符
                    //throw new RuntimeException("无效的括号符号");
            }
        }
        return deque.isEmpty();
    }

    /**
     * 主方法
     * @param args
     */
    public static void main(String[] args) {
        String s = "{[()]}";
        System.out.println(isValib1(s));
        System.out.println(isValib2(s));
    }
}
